package com.rp.article.html.controller;

import com.mongodb.client.gridfs.GridFSBucket;
import com.rp.article.html.config.RabbitMQConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

@Component
@Slf4j
public class RabbitMQArticleConsumer {


    @Autowired
    private GridFSBucket gridFSBucket;

    @Value("${freemarker.html.target}")
    private String htmlTarget;

    @RabbitListener(queues = {RabbitMQConfig.QUEUE_DOWNLOAD_HTML_TEST})
    public void consumer(String payload, Message message){
        log.info("--------->{}",payload);

        String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        log.info("====>{}", receivedRoutingKey);
        String[] split = payload.split(",");
        download(split[0],split[1]);

    }

    public Integer download(String articleId, String articleMongoId) {

        try {
            htmlTarget = htmlTarget + File.separator + articleId + ".html";
            File file = new File(htmlTarget);
            OutputStream fileOutputStream = new FileOutputStream(file);
            gridFSBucket.downloadToStream(new ObjectId(articleMongoId), fileOutputStream);
        }catch (Exception e){

        }

        return HttpStatus.SC_OK;
    }


}
